#ifndef POLL_H
#define POLL_H

#include "core.h"

#if defined(AE_WIN32)
typedef HANDLE __poll_t;
#define INVALID_POLL NULL
#define closepoll CloseHandle
typedef struct {
	OVERLAPPED __parent;
	int type;
	DWORD flags;
	DWORD bytes;
} IOCPOVERLAPPED;
#else
typedef int __poll_t;
#define INVALID_POLL -1
#define closepoll close
#endif

struct timeo_node {
	int seconds;
	ae_time_t expire;
	struct rbnode node;
};

struct poll_provider;
struct poll_customer;

struct poll_provider_method {
	void (*deatch)(struct poll_customer*);
	void (*watch_event)(struct poll_customer*, int);
	void (*reset_timeout)(struct poll_customer*, int);
};

struct poll_provider {
	INHERIT_OBJECT;
	atomic_t nr_customer;
	mutex_t read_lock;
	mutex_t write_lock;
	struct rbtree read_tree;
	struct rbtree write_tree;
	struct poll_provider_method* __method;
};

#define INHERIT_POLL_PROVIDER			\
	struct poll_provider __base

#define TO_POLL_PROVIDER(o)			\
	((struct poll_provider*)o)

struct poll_customer_method {
	int (*maintain)(struct poll_customer*, int);
	int (*before_attath)(struct poll_customer*,__poll_t*,int*);
	void (*after_attath)(struct poll_customer*,int);
	void (*event_arrayed)(struct poll_customer*, int);
};

struct poll_customer {
	INHERIT_OBJECT;
	void* context;
	struct timeo_node read_node;
	struct timeo_node write_node;
	struct poll_provider* __provider;
	struct poll_customer_method* __method;
};

#define INHERIT_POLL_CUSTOMER			\
	struct poll_customer __base

#define TO_POLL_CUSTOMER(o)			\
	((struct poll_customer*)o)

typedef struct {
	INHERIT_POLL_PROVIDER;
	__poll_t poll;
} poll_engine;

#endif
